/**
 * 获取文章详情
 */

import Joi from "joi";
import { getDB } from "~/server/utils/db/mysql";
import {
  getFirstImage,
  getLoginUid,
  responseJson,
  trimMarkdown,
} from "~/server/utils/helper";

export default defineEventHandler(async (event) => {
  //获取数据
  const params = await getQuery(event);

  const schema = Joi.object({
    noteId: Joi.number().required(),
  });
  try {
    const value = await schema.validateAsync(params);
  } catch (e) {
    return responseJson(1, "参数未知", {});
  }

  const con = getDB();
  try {
    //获取用户文章
    const [notesData] = await con.query(
      "SELECT notes.id AS id,notes.title,notes.content_md,notes.uid,notes.created_at,users.nickname,users.avatar FROM `notes` LEFT JOIN `users` ON notes.uid = users.id WHERE `state`=? AND notes.id=?",
      [2, params.noteId]
    );
    if (notesData.length != 1) {
      return responseJson(1, "文章不存在", {});
    }

    return responseJson(0, "获取文章成功哦", {
      id: notesData[0].id,
      title: notesData[0].title,
      subTitle: trimMarkdown(notesData[0].content_md, 300),
      author: {
        id: notesData[0].uid,
        nickname: notesData[0].nickname,
        avatar: notesData[0].avatar,
      },
      content_md: notesData[0].content_md,
      created_at: notesData[0].created_at,
    });
  } catch (e) {
    console.error("获取文章详情失败错误详情:", e);
    if (e instanceof Error) {
      console.error("错误消息:", e.message);
      console.error("错误堆栈:", e.stack);
    }
    // @ts-ignore
    setResponseStatus(event, 500);
    return responseJson(1, "服务器错误", {});
  }
  // 注意：不要关闭连接池！连接池应该保持打开状态以供后续使用
  // 连接池会自动管理连接的获取和释放
});
